import 'package:shared_preferences/shared_preferences.dart';
import 'test_http.dart';

class UserManager {
  static const String _tokenKey = 'token';
  static const String _tokenTypeKey = 'tokenType';
  static const String _refreshTokenKey = 'refreshToken';
  static const String _expiredKey = 'expired';
  static const String _refreshExpiredKey = 'refreshExpired';

  // 保存登录信息
  static Future<void> saveLoginInfo(LoginTokenModel loginInfo) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, loginInfo.token ?? '');
    await prefs.setString(_tokenTypeKey, loginInfo.tokenType ?? '');
    await prefs.setString(_refreshTokenKey, loginInfo.refreshToken ?? '');
    await prefs.setString(_expiredKey, loginInfo.expired ?? '');
    await prefs.setString(_refreshExpiredKey, loginInfo.refreshExpired ?? '');
  }

  // 获取登录信息
  static Future<LoginTokenModel?> getLoginInfo() async {
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString(_tokenKey);
    
    if (token == null || token.isEmpty) {
      return null;
    }
    
    return LoginTokenModel(
      token: token,
      tokenType: prefs.getString(_tokenTypeKey),
      refreshToken: prefs.getString(_refreshTokenKey),
      expired: prefs.getString(_expiredKey),
      refreshExpired: prefs.getString(_refreshExpiredKey),
    );
  }

  // 检查是否已登录
  static Future<bool> isLoggedIn() async {
    final loginInfo = await getLoginInfo();
    if (loginInfo == null || loginInfo.token == null || loginInfo.token!.isEmpty) {
      return false;
    }
    
    // 检查token是否过期（如果有过期时间）
    if (loginInfo.expired != null && loginInfo.expired!.isNotEmpty) {
      try {
        final expiredTime = DateTime.parse(loginInfo.expired!);
        if (DateTime.now().isAfter(expiredTime)) {
          await clearLoginInfo(); // 清除过期的登录信息
          return false;
        }
      } catch (e) {
        print('解析过期时间失败: $e');
      }
    }
    
    return true;
  }

  // 获取当前token
  static Future<String?> getCurrentToken() async {
    final loginInfo = await getLoginInfo();
    return loginInfo?.token;
  }

  // 清除登录信息
  static Future<void> clearLoginInfo() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_tokenKey);
    await prefs.remove(_tokenTypeKey);
    await prefs.remove(_refreshTokenKey);
    await prefs.remove(_expiredKey);
    await prefs.remove(_refreshExpiredKey);
  }
}